package br.com.simora.manager;

import java.io.File;
import java.util.Date;

import javax.inject.Inject;

import org.apache.log4j.Logger;

import br.com.simora.arquivo.ArquivoDAO;
import br.com.simora.crawler.AbstractCrawler;
import br.com.simora.http.HttpTools;
import br.com.simora.http.RtmpHelper;
import br.com.simora.http.StreamTheWorldHelper;
import br.com.simora.musica.Artista;
import br.com.simora.musica.Musica;
import br.com.simora.radio.Radio;

import com.google.gson.Gson;

public class GenericFPRobot extends AbstractCrawler {
	private static Logger logger = Logger.getLogger(GenericFPRobot.class);
	@Inject private ArquivoDAO arquivoDAO;
	@Inject private RtmpHelper rtmpHelper;
	@Inject private StreamTheWorldHelper streamTheWorldHelper;
	
	public GenericFPRobot(Radio radio) {this.radio = radio;}
	
	public GenericFPRobot() {}

	public void setRadio(Radio radio) {
		this.radio = radio;
	}

	public String capturaStream(String url) {
		if("RTMP".equals(radio.getTipo())){
			return rtmpHelper.capturaAudio(radio);
		}
		if("STREAMTHEWORLD".equals(radio.getTipo())){
			return streamTheWorldHelper.capturaStream(radio);
		}
		return "";
	}

	public void recuperaMusica(String path) {
		/*
		 * 1 - enviamos POST com o caminho do arquivo capturado e criado
		 * 2 - preenche objeto Musica
		 * 3 - deleta o arquivo
		 * */
		HttpTools tools = new HttpTools();
		//String retorno = tools.getHTML("http://localhost/wssimora/webservice.php").getConteudo();
		String retorno = tools.sendPostJson("http://simora.python:8000/songs/recognize/", "{\"path\":\""+path+"\"}");
		if(null != retorno && !"".equals(retorno)){
			log.setRetornoFP(retorno);
			logger.info(retorno);
			Gson json = new Gson();
			musica = new Musica();
			musica = json.fromJson(retorno, Musica.class);
		} else {
			log.setDataHoraFim(new Date());
			log.setRetornoFP("");
			log.setStatus("E");
		}
	}
	
	@Override public void recuperaInfo() {
		String path = capturaStream(radio.getUrl());
		if(null != path && !"".equals(path)){
			if(path.contains(File.separator + "var" + File.separator + "music" + File.separator)){
				String pathTemp = path.replace(File.separator + "var" + File.separator + "music" + File.separator, "");
				log.setPathArquivo(pathTemp);
				recuperaMusica(pathTemp);
			} else {
				log.setPathArquivo(path);
				recuperaMusica(path);
			}
			
			if(musica != null){
				artista = new Artista();
				artista = musica.getArtista();
			}
		} else {
			log.setPathArquivo("");
			log.setStatus("E");
		}
		arquivoDAO.deletaArquivo(path);
	}
	
	@Override public void setRadioNome() {
		this.radioNome = radio.getNome();
	}
}